﻿$(function () {

    //select 点击事件
    $('#name').change(function(){
        var options = $("#name option:selected");
        var name = options.val();
        $.ajax({
            type: "post",
            data:{"name":name},
            url:"/Odreceipt/selectOdunit/",
            dataType: "json",
            success: function(data) {

                $('#area').val(data.result.area);

            },
        });
    })

    //初始化下拉框
    // function selectInit(){
    //     $.ajax({
    //         type: "post",
    //         data:{},
    //         url:"/Odreceipt/listOdunit/",
    //         dataType: "json",
    //         success: function(data) {
    //             // var res = eval("(" + data + ")");
    //             var proList = '<option disabled selected value> 请选择商家 </option>';
    //             for (let i=0; i< data.result.length; i++) {
    //                 proList += '<option value='+data.result[i].name+'>'+data.result[i].name+'</option>';
    //                 //$("#name").append("<option value='"+data.result[i].name+"'>"+data.result[i].name+"</option>");
    //             }
    //             $("#name").html(proList);
    //             //select初始化
    //             // $(".selectpicker" ).selectpicker('refresh');
    //             // $(".selectpicker").selectpicker('render');
    //
    //
    //         },
    //     });
    // }
    //初始化时间控件
    jQuery('#qydate').datepicker();

    //初始化select
    // const select2 = $('#name').select2({
    //     language: "zh-CN",
    //     placeholder:'请选择商家',
    //     templateSelection:  selectInit($('#name'))
    // })

    $('#tjButton').click(function () {
        selectPage(1);
    });

    function selectPage(pageCode) {

/*        var options1 = $("#name option:selected");
        var name = options1.val();
        if(name===""||name===null){
            swal("商家名称不能为空!");
            return;
        }*/

        var result = $('input[name="result"]:checked').val();
        if(result===""||result==null||result==="undefined"){
            swal("检查结果不能为空!");
            return;
        }
        var type = $('input[name="type"]:checked').val();
        if(type===""||type==null||type==="undefined"){
            swal("灭火器类型不能为空!");
            return;
        }
        //获取type="checkbox"选中的checkBox的元素
        var  ids = $('input[type="checkbox"]:checked');
        var content = '';
        for (var i = 0; i < ids.length; i ++) {
            //利用三元运算符去点
            content += ids[i].value + (i == ids.length - 1 ? '':';');
        }

        var createdate = new Date().getTime();
        createdate = dateFormat(createdate);

        var qydate = $("#qydate").val();
        if(qydate===""||qydate===null){
            swal("日期不能为空!");
            return;

        }
        var pname = $("#pname").val();
        if(pname===""||pname===null){
            swal("检查人员不能为空!");
            return;
        }
        var date = new Date(qydate);
        qydate = date.getTime();
        qydate = dateFormat(qydate);
        var remark = $("#remark").val();


        //组装参数
        var formData = new FormData();
        // var file = $('#file')[0].files[0];
        // formData.append('file', file);
        formData.append('pname', pname);
        formData.append('remark', remark);
        formData.append('qydate', qydate);
        formData.append('createdate', createdate);

        $.ajax({
            type: "POST",
            url:"/Equipment/addExtinguisherCheck/",
            // data:{"qydate":qydate,"createdate":createdate,"remark":remark},
            data: formData,
            processData: false,
            contentType: false,
            success: function(data) {

                if(data.odreceiptId!==0){
                    swal({title: "提交成功",text: "",	button: "确定"}, function(){
                            //$('#odreceiptform').trigger('reset'); // 重置表单
                            // 重新初始化Bootstrap-select插件
                            // $(".selectpicker" ).selectpicker('refresh');
                            // $(".selectpicker").selectpicker('render');
                            location.reload();
                        }
                    );
                }
                else{
                    swal({title: "提交失败！",text: "请重新录入！",	button: "确定"}
                    );
                }
                // swal({title: "提交成功",text: "",	button: "确定"},
                //     function(){
                //         window.open("/Contract/listContractView","_self");
                //     }
                // );

            },
        });




    }

    function packagingdatatabledata(data){

        var editHtml='<button href="#modal-container-648308" rel="external nofollow" data-toggle="modal" class="btn btn-xs btn-info" onclick="test_env_modify(this)"> <i class="icon-edit bigger-120"></i> </button> <button href="#modal-container-648300" rel="external nofollow" data-toggle="modal" class="btn btn-xs btn-danger" onclick="test_env_delete(this)"> <i class="icon-trash bigger-120"></i> </button>';

        var a=[]; //全部行数据的list
        var banddata = data.result;
        for(var key in banddata){
            var tempObj=[];  //一行数据的list
            var actionHtml='<input data-id ="'+banddata[key].ticketno+'" class="btn" id="update" type="button" value="修改"/>';
            tempObj.push(banddata[key].ticketno);
            tempObj.push(banddata[key].carno);
            tempObj.push(dateFormat(banddata[key].grosstime,""));
            tempObj.push(banddata[key].netweight);
            tempObj.push(banddata[key].productname);
            tempObj.push(banddata[key].username);
            tempObj.push(banddata[key].iccode);
            tempObj.push(banddata[key].syqy);
            tempObj.push(banddata[key].bz);
            // tempObj.push(actionHtml);
            //tempObj.push(editHtml);
            a.push(tempObj);
        }
        return a;

    }

    //修改
    $('#datatable-buttons')
        .on('click', '#update', function( e ) {

            var tno = $(this).attr("data-id");
            $(this).parents().parents().children("td").eq(3).attr("contentEditable","true");
            $(this).attr("style","display:none;");
            $(this).parents().parents().children("td").eq(8).html("<input data-id='"+tno+"' class='btn' id='save' type='button' value='保存' />"+"\n"+"<input data-id='"+tno+"' class='btn' id='cancel' type='button' value='取消' />"+"\n");



        })

    //取消
    $('#datatable-buttons').on('click', '#cancel', function( e ) {

        var tno = $(this).attr("data-id");
        $(this).parents().parents().children("td").eq(3).attr("contentEditable","false");
        $(this).attr("style","display:block;");
        $(this).parents().parents().children("td").eq(8).html("<input data-id='"+tno+"' class='btn' id='update' type='button' value='修改' />"+"\n");



    })


    //保存
    $('#datatable-buttons').on('click', '#save', function( e ) {


        var weight = $(this).parents().parents().children("td").eq(3).text();
        var ticketno = $(this).attr("data-id");
        $.ajax({
            type : "post",
            url : "../servlet/EditDbServlet",
            data:{"weight":weight,"ticketno":ticketno},
            dataType : "json",
            success : function(data) {

                if(data.result==true){

                    swal("保存成功!", "", "success");

                    $('#save').parents().parents().children("td").eq(3).attr("contentEditable","false");
                    $('#save').parents().parents().children("td").eq(8).html("<input data-id='"+ticketno+"' class='btn' id='update' type='button' value='修改' />"+"\n");

                }
                else{

                    swal("保存失败！", "请检查输入数据格式！");

                }

            }
        });


    })


    /**
     * 日期格式化
     * @param Number time 时间戳
     * @param String format 格式
     */
    function dateFormat (time, format) {
        const t = new Date(time)
        // 日期格式
        format = format || 'Y-m-d h:i:s'
        let year = t.getFullYear()
        // 由于 getMonth 返回值会比正常月份小 1
        let month = t.getMonth() + 1
        let day = t.getDate()
        let hours = t.getHours()
        let minutes = t.getMinutes()
        let seconds = t.getSeconds()

        const hash = {
            'y': year,
            'm': month,
            'd': day,
            'h': hours,
            'i': minutes,
            's': seconds
        }
        // 是否补 0
        const isAddZero = (o) => {
            return /M|D|H|I|S/.test(o)
        }
        return format.replace(/\w/g, o => {
            let rt = hash[o.toLocaleLowerCase()]
            return rt >= 10 || isAddZero(o) ? rt : `0${rt}`
        })
    }

})